<template>
  <view class="booking-container">
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="title">立即预约</text>
    </view>
    
    <view class="service-type">
      <text class="section-title">服务方式：</text>
      <view class="radio-group">
        <view class="radio-item" :class="{ active: serviceType === 'inStore' }" @tap="serviceType = 'inStore'">
          <view class="radio-circle" :class="{ checked: serviceType === 'inStore' }"></view>
          <text>到店维修</text>
        </view>
        <view class="radio-item" :class="{ active: serviceType === 'home' }" @tap="serviceType = 'home'">
          <view class="radio-circle" :class="{ checked: serviceType === 'home' }"></view>
          <text>上门取车</text>
        </view>
      </view>
    </view>
    
    <view class="form-section">
      <text class="section-title">客户信息</text>
      <view class="form-item">
        <text class="label">车主姓名：</text>
        <input class="input" type="text" v-model="formData.customerName" placeholder="请输入车主姓名" />
      </view>
      <view class="form-item">
        <text class="label">联系方式：</text>
        <input class="input" type="number" v-model="formData.phone" placeholder="请输入联系方式" />
      </view>
      <view class="form-item">
        <text class="label">预约时间：</text>
        <view class="datetime-container" @tap="chooseBookingTime">
          <text class="datetime-text">{{formData.bookingTime || '请选择预约时间'}}</text>
          <text class="datetime-icon">📅</text>
        </view>
      </view>
      <view class="form-item" v-if="serviceType === 'home'">
        <text class="label">车辆位置：</text>
        <view class="location-input" @tap="getCurrentLocation">
          <text v-if="formData.location" class="location-text">{{ formData.location }}</text>
          <text v-else class="location-placeholder">点击获取当前位置</text>
          <text class="location-icon">📍</text>
        </view>
      </view>
    </view>
    
    <view class="form-section">
      <text class="section-title">车辆信息</text>
      <view class="form-item">
        <text class="label">车辆型号：</text>
        <view class="picker" @tap="showPicker" style="cursor: pointer;">
          <view class="picker-view">
            {{carModelOptions[carModelIndex] || '请选择'}}
            <text class="arrow">▼</text>
          </view>
        </view>
      </view>
      <view class="form-item">
        <text class="label">车牌号：</text>
        <input class="input" type="text" v-model="formData.licensePlate" placeholder="请输入车牌号" />
      </view>
      
      <view class="upload-section">
        <view class="upload-item">
          <text class="upload-label">整车照片：</text>
          <view class="upload-container">
            <view class="upload-btn" v-if="!formData.carPhoto" @tap="uploadCarPhoto">
              <text class="plus-icon">+</text>
              <text class="upload-text">上传照片</text>
            </view>
            <view v-else class="uploaded-image-container">
              <image class="uploaded-image" :src="typeof formData.carPhoto === 'string' ? formData.carPhoto : ''" mode="aspectFill"></image>
              <view class="image-actions">
                <text class="reupload-btn" @tap="uploadCarPhoto">重新上传</text>
                <text class="delete-btn" @tap="deleteImage('carPhoto')">删除</text>
              </view>
            </view>
          </view>
        </view>
        <view class="upload-item">
          <text class="upload-label">维修部位照片：</text>
          <view class="upload-container">
            <view class="upload-btn" v-if="!formData.partPhoto" @tap="uploadPartPhoto">
              <text class="plus-icon">+</text>
              <text class="upload-text">上传照片</text>
            </view>
            <view v-else class="uploaded-image-container">
              <image class="uploaded-image" :src="typeof formData.partPhoto === 'string' ? formData.partPhoto : ''" mode="aspectFill"></image>
              <view class="image-actions">
                <text class="reupload-btn" @tap="uploadPartPhoto">重新上传</text>
                <text class="delete-btn" @tap="deleteImage('partPhoto')">删除</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <button class="submit-btn" @tap="submitBooking">提交</button>
  </view>

  <!-- 时间选择器 -->
  <view v-if="showingDateTimePicker" class="datetime-picker-modal">
    <view class="datetime-picker-container">
      <view class="datetime-picker-header">
        <text class="cancel-btn" @tap="cancelDateTimeSelection">取消</text>
        <text class="picker-title">选择预约时间</text>
        <text class="confirm-btn" @tap="confirmDateTimeSelection">确定</text>
      </view>
      <view class="datetime-picker-content">
        <view class="picker-column">
          <text class="column-title">日期</text>
          <scroll-view class="picker-scroll" scroll-y="true">
            <view class="picker-item" 
                  v-for="(date, index) in dateOptions" 
                  :key="index"
                  :class="{ 'selected': index === tempPickerIndex.date }"
                  @tap="tempPickerIndex.date = index">
              {{ date }}
            </view>
          </scroll-view>
        </view>
        <view class="picker-column">
          <text class="column-title">时间</text>
          <scroll-view class="picker-scroll" scroll-y="true">
            <view class="picker-item" 
                  v-for="(time, index) in timeOptions" 
                  :key="index"
                  :class="{ 'selected': index === tempPickerIndex.time }"
                  @tap="tempPickerIndex.time = index">
              {{ time }}
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      serviceType: 'inStore',
      formData: {
        customerName: '',
        phone: '',
        bookingTime: '',
        location: '',
        licensePlate: '',
        carPhoto: '',
        partPhoto: '',
        carTypeId: '' // 添加车型ID字段
      },
      carModels: [{id: '', name: '请选择'}], // 修改为对象数组，包含id和name
      carModelOptions: [], // 用于picker显示的车型名称数组
      carModelIndex: 0,
      loading: false,
      defaultDateTime: '', // 默认日期时间（当前时间）
      // 日期时间选择器相关数据
      showingDateTimePicker: false,
      dateOptions: [],
      timeOptions: [],
      tempPickerIndex: {
        date: 0,
        time: 0
      }
    }
  },
  onLoad() {
    // 页面加载时获取车辆型号列表
    this.fetchCarTypes()
    
    // 设置最小日期和时间
    this.setMinDateTime()
  },
  
  methods: {
    setMinDateTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = (now.getMonth() + 1).toString().padStart(2, '0')
      const day = now.getDate().toString().padStart(2, '0')
      const hour = now.getHours().toString().padStart(2, '0')
      const minute = now.getMinutes().toString().padStart(2, '0')
      
      // 设置默认日期时间为当前时间，但不限制可选范围
      this.defaultDateTime = `${year}-${month}-${day} ${hour}:${minute}`
      
      // 初始化预约时间为空，让用户手动选择
      this.formData.bookingTime = ''
    },
    
    // 选择预约时间的方法
     chooseBookingTime() {
       // 直接使用自定义日期时间选择器，兼容性更好
       this.showCustomDateTimePicker()
     },
    
    // 自定义日期时间选择器
    showCustomDateTimePicker() {
      // 获取当前日期时间
      const now = new Date()
      const currentYear = now.getFullYear()
      const currentMonth = now.getMonth() + 1
      const currentDay = now.getDate()
      const currentHour = now.getHours()
      const currentMinute = now.getMinutes()
      
      // 获取月份和日期
      const monthCount = 12
      const dayCount = 31
      const hourCount = 24
      const minuteCount = 60
      
      // 创建日期选项
      const dateOptions = []
      for (let m = 1; m <= monthCount; m++) {
        const monthStr = String(m).padStart(2, '0')
        const monthDays = new Date(currentYear, m, 0).getDate()
        
        for (let d = 1; d <= monthDays; d++) {
          const dayStr = String(d).padStart(2, '0')
          // 只显示从今天起的日期
          const dateToCheck = new Date(currentYear, m - 1, d)
          if (dateToCheck >= new Date(currentYear, currentMonth - 1, currentDay)) {
            dateOptions.push(`${currentYear}-${monthStr}-${dayStr}`)
          }
        }
      }
      
      // 创建时间选项（每15分钟一个，只显示当前时间之后的时间）
      const timeOptions = []
      
      for (let h = 0; h < hourCount; h++) {
        for (let m = 0; m < minuteCount; m += 15) {
          // 检查是否是今天的日期
          if (dateOptions.length > 0 && dateOptions[0] === `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(currentDay).padStart(2, '0')}`) {
            // 对于今天，只显示当前时间之后的时间选项
            const isAfterCurrentTime = h > currentHour || (h === currentHour && m >= currentMinute)
            if (!isAfterCurrentTime) continue;
          }
          
          const hourStr = String(h).padStart(2, '0')
          const minuteStr = String(m).padStart(2, '0')
          timeOptions.push(`${hourStr}:${minuteStr}`)
        }
      }
      
      // 创建临时选择器的索引
      this.tempPickerIndex = {
        date: 0,
        time: 0
      }
      
      // 找到今天的日期在列表中的位置
      const todayDateStr = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(currentDay).padStart(2, '0')}`
      const todayIndex = dateOptions.indexOf(todayDateStr)
      if (todayIndex !== -1) {
        this.tempPickerIndex.date = todayIndex
      }
      
      // 找到当前时间在列表中的位置
      const currentTimeIndex = timeOptions.findIndex(time => {
        const [h, m] = time.split(':').map(Number)
        return h === currentHour && Math.floor(currentMinute / 15) * 15 === m
      })
      if (currentTimeIndex !== -1) {
        this.tempPickerIndex.time = currentTimeIndex
      }
      
      // 保存生成的选项
      this.dateOptions = dateOptions
      this.timeOptions = timeOptions
      
      // 显示选择器
      this.showingDateTimePicker = true
    },
    
    // 确认选择日期时间
    confirmDateTimeSelection() {
      // 使用已保存的选项，不再重复生成
      // 确保选项已初始化
      if (!this.dateOptions.length || !this.timeOptions.length) {
        uni.showToast({
          title: '选项加载中，请重试',
          icon: 'none'
        })
        return
      }
      
      // 获取选择的日期和时间
      const selectedDate = this.dateOptions[this.tempPickerIndex.date] || this.dateOptions[0]
      const selectedTime = this.timeOptions[this.tempPickerIndex.time] || this.timeOptions[0]
      
      // 组合日期和时间
      const selectedDateTime = `${selectedDate} ${selectedTime}`
      
      // 设置选择的日期时间
      this.formData.bookingTime = selectedDateTime
      console.log('设置的预约时间:', selectedDateTime)
      
      // 关闭选择器
      this.showingDateTimePicker = false
      
      // 显示成功提示
      uni.showToast({
        title: '预约时间设置成功',
        icon: 'success'
      })
    },
    
    // 取消选择日期时间
    cancelDateTimeSelection() {
      this.showingDateTimePicker = false
    },
    onDateTimeChange(e) {
      const selectedDateTime = e.detail.value
      console.log('选择的日期时间:', selectedDateTime)
      
      // 直接使用选择的日期时间，不需要额外验证
      // 因为picker组件的:start属性已经限制了不能选择当前时间之前的时间
      this.formData.bookingTime = selectedDateTime
      
      console.log('预约时间已设置:', this.formData.bookingTime)
    },
    
    goBack() {
      // 返回上一页
      uni.navigateBack()
    },
    // 获取车辆型号列表
    fetchCarTypes() {
      this.loading = true
      uni.request({
        url: 'http://localhost:8080/cc/merchant/carTypeList',
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 数据结构示例: {"msg":"success","code":200,"data":[{"id":1,"name":"雪福来0169"},{"id":2,"name":"奥迪A6"}]}
            // 将获取的数据添加到车型列表中，保留第一个"请选择"选项
            const carTypes = res.data.data || []
            this.carModels = [{id: '', name: '请选择'}, ...carTypes]
            // 提取车型名称数组用于picker显示
            this.carModelOptions = this.carModels.map(model => model.name)
            console.log('获取车辆型号成功:', this.carModels)
          } else {
            console.error('获取车辆型号失败:', res.data)
            uni.showToast({
              title: '获取车辆型号失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    showPicker() {
      console.log('点击了车型选择器，可用车型:', this.carModelOptions)
      if (this.carModelOptions.length === 0) {
        console.warn('车型列表为空')
        uni.showToast({
          title: '车型列表加载中...',
          icon: 'loading'
        })
        return
      }
      
      // 使用uni.showActionSheet来代替picker组件
      const options = this.carModelOptions.slice(1) // 跳过"请选择"选项
      uni.showActionSheet({
        itemList: options,
        success: (res) => {
          if (!res.cancel) {
            // 实际索引需要+1，因为跳过了第一个选项
            this.carModelIndex = res.tapIndex + 1
            const selectedModel = this.carModels[this.carModelIndex]
            if (selectedModel) {
              this.formData.carTypeId = selectedModel.id
              console.log('选中的车型:', selectedModel)
              uni.showToast({
                title: `已选择: ${selectedModel.name}`,
                icon: 'success'
              })
            }
          }
        },
        fail: (err) => {
          console.error('选择车型失败:', err)
        }
      })
    },
    onCarModelChange(e) {
      // 兼容原有的onChange事件处理
      console.log('onChange事件触发:', e)
      this.carModelIndex = e.detail.value
      const selectedModel = this.carModels[this.carModelIndex]
      if (selectedModel) {
        this.formData.carTypeId = selectedModel.id
        console.log('选中的车型:', selectedModel)
      }
    },
    // 选择并上传整车照片
    uploadCarPhoto() {
      this.chooseAndUploadImage('carPhoto')
    },
    
    // 选择并上传维修部位照片
    uploadPartPhoto() {
      this.chooseAndUploadImage('partPhoto')
    },
    
    // 选择图片
    chooseAndUploadImage(fieldName) {
      console.log(`开始选择${fieldName === 'carPhoto' ? '整车' : '维修部位'}图片`)
      
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
            console.error('未获取到图片路径')
            uni.showToast({
              title: '获取图片失败',
              icon: 'none',
              duration: 2000
            })
            return
          }
          
          const tempFilePath = res.tempFilePaths[0]
          console.log('选择的图片路径:', tempFilePath)
          
          // 上传图片（uploadFile方法内部会显示加载提示）
          this.uploadFile(tempFilePath, fieldName)
        },
        fail: (err) => {
          const errMsg = err.errMsg || ''
          console.error('选择图片失败:', errMsg)
          
          // 只有非用户取消的错误才显示提示
          if (!errMsg.includes('cancel')) {
            uni.showToast({
              title: '选择图片失败，请重试',
              icon: 'none',
              duration: 2000
            })
          }
        },
        complete: () => {
          console.log(`图片选择操作完成: ${fieldName}`)
        }
      })
    },
    
    // 上传文件到服务器
    uploadFile(filePath, fieldName) {
      // 显示加载提示
      uni.showLoading({
        title: '上传中...',
      })
      
      uni.uploadFile({
        url: 'http://localhost:8080/file/upload',
        filePath: filePath,
        name: 'file',
        method: 'POST',
        header: {
          'content-type': 'multipart/form-data'
        },
        success: (uploadRes) => {
          console.log('上传响应状态码:', uploadRes.statusCode)
          console.log('上传响应数据:', uploadRes.data)
          
          try {
            let data;
            // 尝试解析响应数据
            try {
              data = JSON.parse(uploadRes.data)
              console.log('解析后的上传数据:', data)
            } catch (parseError) {
              console.error('JSON解析失败:', parseError)
              throw new Error('服务器返回格式不正确')
            }
            
            // 根据状态码和响应数据判断是否成功
            if (uploadRes.statusCode === 200) {
              if (data && data.code === 200) {
                // 确保存储的是字符串类型的图片地址
                let imageUrl = '';
                if (typeof data.data === 'string') {
                  imageUrl = data.data;
                } else if (data.data && typeof data.data === 'object') {
                  // 如果data.data是对象，尝试获取其中的url字段或转换为字符串
                  imageUrl = data.data.url || JSON.stringify(data.data);
                } else {
                  imageUrl = String(data.data || '');
                }
                
                this.formData[fieldName] = imageUrl;
                console.log(`图片地址已保存: ${imageUrl}`);
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
              } else {
                // 服务器返回了非成功状态
                throw new Error(data.msg || '上传失败')
              }
            } else {
              // HTTP状态码不是200
              throw new Error(`服务器错误: ${uploadRes.statusCode}`)
            }
          } catch (error) {
            console.error('处理上传结果失败:', error.message)
            uni.showToast({
              title: error.message || '处理上传结果失败',
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: (err) => {
          console.error('上传请求失败:', err.errMsg)
          uni.showToast({
            title: '网络请求失败，请检查连接',
            icon: 'none',
            duration: 2000
          })
        },
        complete: () => {
          // 确保隐藏加载提示
          setTimeout(() => {
            uni.hideLoading()
          }, 100)
        }
      })
    },
    // 删除图片
    deleteImage(fieldName) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            this.formData[fieldName] = ''
            console.log(`已删除${fieldName}图片`)
          }
        }
      })
    },
    
    // 获取当前位置
    getCurrentLocation() {
      console.log('开始获取当前位置...')
      
      // 显示加载提示
      uni.showLoading({
        title: '定位中...',
      })
      
      // 获取当前位置
      uni.getLocation({
        type: 'gcj02',
        altitude: true,
        success: (res) => {
          console.log('获取位置成功:', res)
          
          // 坐标转地址（逆地理编码）
          this.reverseGeocode(res.latitude, res.longitude)
        },
        fail: (err) => {
          console.error('获取位置失败:', err)
          this.handleLocationError(err)
        },
        complete: () => {
          // 隐藏加载提示
          setTimeout(() => {
            uni.hideLoading()
          }, 100)
        }
      })
    },
    
    // 坐标转地址
    reverseGeocode(latitude, longitude) {
      console.log('开始逆地理编码:', { latitude, longitude })
      
      // 使用微信地图API进行逆地理编码
      // 这里使用模拟数据，实际应用中应调用真实的地理编码服务
      // 例如可以调用腾讯地图API、高德地图API等
      
      try {
        // 模拟地址数据（移除经纬度信息）
        const mockAddress = '北京市朝阳区建国路88号' + (Math.random() > 0.5 ? ' 世贸天阶购物中心 B座 地下停车场' : ' 国贸中心三期 地下二层')
        
        // 保存位置信息
        this.formData.location = mockAddress
        console.log('位置信息已保存:', mockAddress)
        
        uni.showToast({
          title: '位置获取成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('处理位置信息时出错:', error)
        uni.showToast({
          title: '处理位置信息失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 处理定位错误
    handleLocationError(err) {
      console.error('定位错误详情:', err)
      
      let errorTitle = '定位失败'
      let errorMsg = '请检查您的定位权限设置'
      
      // 根据错误码提供更具体的错误信息
      if (err.errMsg) {
        const errMsg = err.errMsg.toLowerCase()
        
        if (errMsg.includes('auth deny') || errMsg.includes('auth denied')) {
          errorTitle = '定位权限被拒绝'
          errorMsg = '请在设置中允许应用获取您的位置信息'
        } else if (errMsg.includes('position unavailable')) {
          errorTitle = '位置信息不可用'
          errorMsg = '当前环境无法获取位置信息，请稍后重试'
        } else if (errMsg.includes('timeout')) {
          errorTitle = '定位超时'
          errorMsg = '获取位置信息超时，请检查网络连接后重试'
        }
      }
      
      // 显示详细的错误提示
      uni.showModal({
        title: errorTitle,
        content: errorMsg,
        showCancel: false,
        confirmText: '知道了',
        success: (res) => {
          if (res.confirm && (err.errMsg && (err.errMsg.toLowerCase().includes('auth deny') || err.errMsg.toLowerCase().includes('auth denied')))) {
            // 如果是权限问题，可以引导用户去设置页面
            console.log('用户需要去设置页面开启定位权限')
          }
        }
      })
    },
    
    submitBooking() {
      // 表单验证
      if (!this.formData.customerName) {
        uni.showToast({
          title: '请输入车主姓名',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入联系方式',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.bookingTime) {
        uni.showToast({
          title: '请选择预约时间',
          icon: 'none'
        })
        return
      }
      
      if (this.serviceType === 'home' && !this.formData.location) {
        uni.showToast({
          title: '请获取车辆位置',
          icon: 'none'
        })
        return
      }
      
      // 验证手机号格式
      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入联系方式',
          icon: 'none'
        })
        return
      }
      // 中国大陆手机号验证：11位数字，以1开头
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号格式',
          icon: 'none'
        })
        return
      }
      
      // 验证车牌号
      if (!this.formData.licensePlate) {
        uni.showToast({
          title: '请输入车牌号',
          icon: 'none'
        })
        return
      }
      // 中国车牌号验证格式（简化版）：汉字+字母+5位数字/字母组合
      const plateRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
      if (!plateRegex.test(this.formData.licensePlate)) {
        uni.showToast({
          title: '请输入正确的车牌号格式',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.carTypeId) {
        uni.showToast({
          title: '请选择车辆型号',
          icon: 'none'
        })
        return
      }
      
      // 验证整车照片（必填）
      if (!this.formData.carPhoto) {
        uni.showToast({
          title: '请上传整车照片',
          icon: 'none'
        })
        return
      }
      
      // 验证维修部位照片（必填）
      if (!this.formData.partPhoto) {
        uni.showToast({
          title: '请上传维修部位照片',
          icon: 'none'
        })
        return
      }
      
      // 显示加载提示
      uni.showLoading({
        title: '提交中...',
      })
      
      // 准备提交的数据，根据数据库表结构映射字段
      const submitData = {
        type: this.serviceType === 'inStore' ? '到店维修' : '上门取车', // 将服务类型映射为对应的中文文字
        name: this.formData.customerName,
        phone: this.formData.phone,
        reservationTime: this.formData.bookingTime,
        location: this.formData.location || '',
        carTypeId: this.formData.carTypeId,
        carNum: this.formData.licensePlate,
        vehiclePhotos: this.formData.carPhoto || '', // 提交整车图片的地址
        repairPhotos: this.formData.partPhoto || '', // 提交维修部位图片的地址
        status: 0 // 维修状态：0已预约
      }
      
      console.log('提交到服务器的数据:', submitData)
      
      // 发送POST请求
      uni.request({
        url: 'http://localhost:8080/cc/merchant/repairReservation',
        method: 'GET',
        data: submitData,
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          console.log('提交响应:', res)
          
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 提交成功，跳转到成功页面
            const bookingId = res.data.data?.id || Date.now().toString()
            
            // 额外调用insertOrder接口，提交预约时间
            uni.request({
              url: 'http://localhost:8080/cc/merchant/insertOrder',
              method: 'GET',
              data: {
                reservationTime: this.formData.bookingTime
              },
              success: (orderRes) => {
                console.log('insertOrder接口调用成功:', orderRes)
              },
              fail: (orderErr) => {
                console.error('insertOrder接口调用失败:', orderErr)
              }
            })
            
            uni.showToast({
              title: '预约提交成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  uni.navigateTo({
                    url: `/pages/booking-success/booking-success?bookingId=${bookingId}`
                  })
                }, 1500)
              }
            })
          } else {
            // 提交失败
            uni.showToast({
              title: res.data?.msg || '提交失败，请重试',
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: (err) => {
          console.error('网络请求失败:', err)
          uni.showToast({
            title: '网络请求失败，请检查连接',
            icon: 'none',
            duration: 2000
          })
        },
        complete: () => {
          // 隐藏加载提示
          setTimeout(() => {
            uni.hideLoading()
          }, 100)
        }
      })
    }
  }
}
</script>

<style scoped>
.booking-container {
  padding: 0 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  padding: 60rpx 0 30rpx 0;
  text-align: center;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  margin-top: 10px;
}

.back-icon {
  font-size: 40rpx;
  font-weight: bold;
}

.header-right {
  width: 60rpx; /* 为了平衡布局 */
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin: auto;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 30rpx 0 20rpx 0;
  display: block;
}

.service-type {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
  border-radius: 10rpx;
}

.radio-group {
  display: flex;
  gap: 40rpx;
  margin-top: 20rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx 25rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
}

.radio-item.active {
  border-color: #007aff;
}

.radio-circle {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  position: relative;
}

.radio-circle.checked {
  border-color: #007aff;
}

.radio-circle.checked::after {
  content: '';
  position: absolute;
  width: 16rpx;
  height: 16rpx;
  background-color: #007aff;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.form-section {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
  border-radius: 10rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
}

.label {
  font-size: 28rpx;
  color: #333;
  width: 200rpx;
}

.input {
  flex: 1;
  height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.location-input {
  flex: 1;
  min-height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  cursor: pointer;
  background-color: #fff;
}

.location-input:active {
  background-color: #f5f5f5;
}

.location-text {
  flex: 1;
  color: #333;
  font-size: 28rpx;
  word-break: break-all;
  word-wrap: break-word;
  line-height: 1.4;
}

.location-placeholder {
  color: #999;
  font-size: 28rpx;
}

.location-icon {
  margin-left: 10rpx;
  font-size: 28rpx;
}

/* 日期时间选择器样式 */
.datetime-container {
  flex: 1;
  min-height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  background-color: #fff;
  transition: all 0.3s;
}

.datetime-container:active {
  background-color: #f5f5f5;
  border-color: #cbd5e0;
}

.datetime-text {
  flex: 1;
  color: #666;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.datetime-icon {
  font-size: 32rpx;
  margin-left: 10rpx;
}

.picker {
  flex: 1;
  height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.picker-view {
  font-size: 28rpx;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.picker-view .arrow {
  font-size: 20rpx;
  color: #999;
}

.upload-section {
  margin-top: 20rpx;
}

.upload-item {
  margin-bottom: 30rpx;
}

.upload-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
}

.upload-container {
  margin-top: 15rpx;
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.uploaded-image-container {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
  background-color: #f5f5f5;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: space-around;
  padding: 10rpx 0;
}

.reupload-btn,
.delete-btn {
  color: #fff;
  font-size: 22rpx;
}

.delete-btn {
  color: #ff4d4f;
}

.plus-icon {
  font-size: 60rpx;
  color: #999;
}

.upload-text {
  font-size: 26rpx;
  color: #999;
}

.submit-btn {
  margin-top: 50rpx;
  margin-bottom: 50rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 8rpx;
}

/* 可视化时间选择器样式 */
.datetime-picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.datetime-picker-container {
  background-color: #fff;
  border-radius: 10rpx;
  width: 80%;
  max-width: 600rpx;
  max-height: 70vh;
  overflow: hidden;
}

.datetime-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.cancel-btn,
.confirm-btn {
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
}

.cancel-btn {
  color: #666;
}

.confirm-btn {
  color: #007aff;
}

.datetime-picker-content {
  display: flex;
  padding: 20rpx 0;
  max-height: 500rpx;
}

.picker-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.column-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.picker-scroll {
  flex: 1;
  height: 300rpx;
}

.picker-item {
  padding: 20rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.2s;
}

.picker-item:hover {
  background-color: #f5f5f5;
}

.picker-item.selected {
  color: #007aff;
  font-weight: bold;
  background-color: #e6f7ff;
}
</style>